<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchConditionNum="7" :searchFunc="queryFunc" :resetFunc="onReset">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker ref="dateRangePicker" v-model:value="vdata.searchData['queryDateRange']" customDateRangeType="dateTime" />
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData.unionOrderId" :placeholder="'退款/支付/渠道/商户退款号'" />
        <JeepaySearchInfoInput v-model:value="vdata.searchData['mchNo']" placeholder="商户号" :textUpStyle="true" :mchNoAndName="true" showType="MCH" />
        <jeepay-text-up v-model:value="vdata.searchData.storeId" :placeholder="'门店ID'" class="table-search-item" />
        <jeepay-text-up v-model:value="vdata.searchData.storeName" :placeholder="'门店名称'" class="table-search-item" />

        <jeepay-text-up v-model:value="vdata.searchData.isvNo" :placeholder="'服务商号'" />
        <jeepay-text-up v-model:value="vdata.searchData.appId" :placeholder="'应用AppId'" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.state" placeholder="退款状态">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">订单生成</a-select-option>
            <a-select-option value="1">退款中</a-select-option>
            <a-select-option value="2">退款成功</a-select-option>
            <a-select-option value="3">退款失败</a-select-option>
          </a-select>
        </a-form-item>
        <!-- <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.mchType" placeholder="商户类型">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="1">普通商户</a-select-option>
            <a-select-option value="2">特约商户</a-select-option>
          </a-select>
        </a-form-item> -->

        <JeepaySelect ref="ifCodeRef" placeholder="支付接口" :reset="isReset">
          <a-select v-model:value="vdata.searchData.ifCode" @change="ifCodeRef.textupHandle()">
            <a-select-option value="">全部</a-select-option>
            <template v-for="(item) in vdata.ifCodeList" :key="item.ifCode">
              <a-select-option :value="item.ifCode">{{ item.ifName }}[{{ item.ifCode }}]</a-select-option>
            </template>
          </a-select>
        </JeepaySelect>
      </JeepaySearchForm>
      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :initData="true"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        rowKey="refundOrderId"
        :tableRowCrossColor="true"
        :statisticsIsShow="$access('ENT_REFUND_ORDER_COUNT')"
        :autoRefTableConfig="{defaultOpen: true, interval: 180}"
        :tableExportFunc="tableExportFunc"
        @btnLoadClose="vdata.btnLoading=false"
      >
        <template #statistics>
          <div class="statistics-list">
            <div v-for="(item, index) in orderCountList" :key="index" class="item">
              <div v-if="item.type == 'line'" class="line" />
              <div class="title">{{ item.title }}</div>
              <div v-if="item.title" class="amount" :style="{color: item.textColor}">
                <!-- <span v-if="item.symbol" class="symbol">{{ item.symbol == 'add' ? '+' : '-' }}</span> -->
                <span class="amount-num">{{ item.content }}</span>{{ item.unit?item.unit:'元' }}
              </div>
            </div>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'payAmount'">
            <b>￥{{ record.payAmount/100 }}</b>
          </template>

          <template v-if="column.key === 'refundAmount'">
            <b>￥{{ record.refundAmount/100 }}</b>
          </template>

          <template v-if="column.key == 'refundFeeAmount'">
            <b>￥{{ record.refundFeeAmount/100 }}</b>
          </template>

          <template v-if="column.key === 'state'">
            <a-tag
              :key="record.state"
              :color="record.state === 0?'blue':record.state === 1?'orange':record.state === 2?'green':'volcano'"
            >
              {{ record.state === 0?'订单生成':record.state === 1?'退款中':record.state === 2?'退款成功':record.state === 3?'退款失败':record.state === 4?'任务关闭':'未知' }}
            </a-tag>
          </template>

          <template v-if="column.key === 'refund'">
            <div class="order-list">
              <p><span style="color:#729ED5;background:#e7f5f7">支付</span>{{ record.payOrderId }}</p>
              <p v-if="record.channelPayOrderNo" style="margin-bottom: 0;">
                <span style="color:#fff;background:#E09C4D">渠道</span>
                <a-tooltip v-if="record.channelPayOrderNo.length > record.payOrderId.length" placement="bottom" style="font-weight: normal;">
                  <template #title>
                    <span>{{ record.channelPayOrderNo }}</span>
                  </template>
                  {{ changeStr2ellipsis(record.channelPayOrderNo, record.payOrderId.length) }}
                </a-tooltip>
                <span v-else style="font-weight: normal;">{{ record.channelPayOrderNo }}</span>
              </p>
            </div>
          </template>

          <template v-if="column.key === 'pay'">
            <div class="order-list">
              <p><span style="color:#729ED5;background:#e7f5f7">退款</span>{{ record.refundOrderId }}</p>
              <p style="margin-bottom: 0;">
                <span style="color:#56cf56;background:#d8eadf">商户</span>
                <a-tooltip v-if="record.mchRefundNo.length > record.payOrderId.length" placement="bottom" style="font-weight: normal;">
                  <template #title>
                    <span>{{ record.mchRefundNo }}</span>
                  </template>
                  {{ changeStr2ellipsis(record.mchRefundNo, record.refundOrderId.length) }}
                </a-tooltip>
                <span v-else style="font-weight: normal;">{{ record.mchRefundNo }}</span>
              </p>
            </div>
          </template>

          <template v-if="column.key === 'ifCode'">
            <span>{{ record.ifName }} ({{ record.ifCode }})</span>
          </template>

          <template v-if="column.key === 'op'">
            <!-- 操作列插槽 -->
           
            <a-button v-if="$access('ENT_REFUND_ORDER_VIEW')" type="link" @click="detailFunc(record.refundOrderId)">详情</a-button>
          </template>

          <template v-if="column.key === 'mchName'" />

          <template v-if="column.key === 'mchName'" />
        </template>
      </JeepayTable>
    </a-card>
    <!-- 日志详情抽屉 -->
    <template>
      <a-drawer
        width="50%"
        placement="right"
        :closable="true"
        :visible="vdata.visible"
        :title="vdata.visible === true? '退款订单详情':''"
        @close="onClose"
      >
        <a-row justify="space-between" type="flex">
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="所属系统">
                {{ vdata.detailData.mchType === 1?'普通商户':vdata.detailData.mchType === 2?'特约商户':'未知' }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="服务商号">
                {{ vdata.detailData.isvNo }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="退款订单号">
                <a-tag color="purple">
                  {{ vdata.detailData.refundOrderId }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="商户号">
                {{ vdata.detailData.mchNo }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="支付订单号">
                {{ vdata.detailData.payOrderId }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="商户退款单号">
                {{ vdata.detailData.mchRefundNo }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="渠道支付订单号">
                {{ vdata.detailData.channelPayOrderNo }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="应用APPID">
                {{ vdata.detailData.appId }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="门店ID">
                {{ vdata.detailData.storeId }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="门店名称">
                {{ vdata.detailData.storeName }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="支付金额">
                <a-tag color="green">
                  {{ vdata.detailData.payAmount/100 }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="退款金额">
                <a-tag color="green">
                  {{ vdata.detailData.refundAmount/100 }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="手续费退还金额">
                <a-tag color="green">
                  {{ vdata.detailData.refundFeeAmount/100 }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="订单状态">
                <a-tag :color="vdata.detailData.state === 0?'blue':vdata.detailData.state === 1?'orange':vdata.detailData.state === 2?'green':'volcano'">
                  {{ vdata.detailData.state === 0?'订单生成':vdata.detailData.state === 1?'退款中':vdata.detailData.state === 2?'退款成功':vdata.detailData.state === 3?'退款失败':vdata.detailData.state === 4?'任务关闭':'未知' }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="创建时间">
                {{ vdata.detailData.createdAt }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="更新时间">
                {{ vdata.detailData.updatedAt }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="退款成功时间">
                {{ vdata.detailData.successTime }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-divider />
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="接口代码">
                {{ vdata.detailData.ifCode }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="货币代码">
                {{ vdata.detailData.currency }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="方式代码">
                {{ vdata.detailData.wayCode }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="12">
            <a-descriptions>
              <a-descriptions-item label="客户端IP">
                {{ vdata.detailData.clientIp }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :sm="24">
            <a-descriptions>
              <a-descriptions-item label="异步通知地址">
                {{ vdata.detailData.notifyUrl }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
        </a-row>
        <a-divider />
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="渠道订单号">
              {{ vdata.detailData.channelOrderNo }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="渠道错误码">
              {{ vdata.detailData.errCode }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="渠道错误描述">
              {{ vdata.detailData.errMsg }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="24">
          <span style="color: black;">渠道额外参数:</span>
          <a-form-item>
            <a-textarea
              v-model:value="vdata.detailData.channelExtra"
              disabled="disabled"
              style="height: 100px;color: black;margin-top: 10px; "
            />
          </a-form-item>
        </a-col>
        <a-divider />
        <a-col :sm="24">
          <span style="color: black;">扩展参数:</span>
          <a-form-item label="">
            <a-textarea
              v-model:value="vdata.detailData.extParam"
              disabled="disabled"
              style="height: 100px;color: black; margin-top: 10px;"
            />
          </a-form-item>
        </a-col>
        <a-col :sm="24">
          <span style="color: black;">备注:</span>
          <a-form-item>
            <a-textarea
              v-model:value="vdata.detailData.remark"
              disabled="disabled"
              style="height: 100px;color: black; margin-top: 10px;"
            />
          </a-form-item>
        </a-col>
      </a-drawer>
    </template>
  </page-header-wrapper>
</template>
<script setup lang="ts">
import { API_URL_REFUND_ORDER_LIST, req, $exportExcel, exportExcelUrl, $refundOrderCount, API_URL_IFDEFINES_LIST } from '@/api/manage'
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import fileDownload from 'js-file-download'

// 导入全局函数
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

// infoTable组件
const infoTable = ref()
const ifCodeRef = ref()
const dateRangePicker = ref()
let isReset = ref(0) // 下拉搜索框是否重置

  // eslint-disable-next-line no-unused-vars
    const tableColumns = ref([
      { key: 'pay', title: '退款订单号' ,fixed: 'left',},
      { key: 'refund', title: '支付订单号' },
      { key: 'storeName', title: '门店名称', dataIndex: 'storeName', defaultHidden: true },
      { key: 'storeId', title: '门店ID', dataIndex: 'storeId', defaultHidden: true },
      { key: 'ifCode', title: '支付接口'},
      { key: 'payAmount', title: '支付金额', ellipsis: true},
      { key: 'refundAmount', title: '退款金额', ellipsis: true},
      { key: 'refundFeeAmount', title: '手续费退还金额' },
      { key: 'state', title: '状态' },
      { key: 'createdAt', dataIndex: 'createdAt', title: '创建日期'  },
      { key: 'op', title: '操作',  fixed: 'right'}
    ])

    const vdata : any = reactive({
          btnLoading: false,
          searchData: {queryDateRange: 'today'} as any,
          visible: false,
          detailData: {} as any
    })

    onMounted( () => {
      if($access('ENT_PC_IF_DEFINE_LIST')){
        req.list(API_URL_IFDEFINES_LIST, {state:1}).then((res) => {
          vdata.ifCodeList = res
        })
      }

      getOrderCount()
    })

    let orderCountList:any = ref([]) // 数据统计数组
    // 数据统计
    const getOrderCount = () => {

      if(!$access('ENT_REFUND_ORDER_COUNT')){
        return false
      }

      $refundOrderCount(vdata.searchData).then( res => {
        orderCountList.value = [
          {title: '退款金额', symbol: 'add', textColor: '#1A66FF', content: (res.refundAmount / 100).toFixed(2)},
          {type: 'line'},
          {title: '退款笔数', content: res.refundCount, unit: '笔'},
          {type: 'line'},
          {title: '退还手续费金额',symbol: 'sub', content: (res.refundFeeAmount / 100).toFixed(2)},
        ]
      })
    }

    function onReset(){
      isReset.value++ // 下拉搜索框重置
      //重置搜索内容
      dateRangePicker.value.returnSelectModel()
      vdata.searchData = { queryDateRange: 'today' }
    }
    
    function queryFunc () {
      vdata.btnLoading = true
      infoTable.value.refTable(true)
      getOrderCount()
    }
    // 请求table接口数据
    function reqTableDataFunc(params) {
      return req.list(API_URL_REFUND_ORDER_LIST, params)
    }
    function detailFunc (recordId) {
      req.getById(API_URL_REFUND_ORDER_LIST, recordId).then(res => {
        vdata.detailData = res
      })
      vdata.visible = true
    }
    function onClose () {
      vdata.visible = false
    }
    function changeStr2ellipsis (orderNo, baseLength) {
      const halfLengh = baseLength / 2
      return orderNo.substring(0, halfLengh - 1) + '...' + orderNo.substring(orderNo.length - halfLengh, orderNo.length)
    }

    function tableExportFunc(){
      return $exportExcel(exportExcelUrl.refundOrder, Object.assign(vdata.searchData, {'pageSize': -1})).then(res => {
         fileDownload(res.data, '退款订单.xlsx')
      }).catch ((error) =>{console.log(error)} )
    }

</script>
<style lang="less" scoped>
.order-list {
  -webkit-text-size-adjust:none;
  font-size: 12px;
  display: flex;
  flex-direction: column;

  p {
    white-space:nowrap;
    span {
      display: inline-block;
      font-weight: 800;
      height: 16px;
      line-height: 16px;
      width: 35px;
      border-radius: 5px;
      text-align: center;
      margin-right: 2px;
    }
  }
}
</style>
